package com.citycloud.ccuap.tc.admin.projectapp;


import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.citycloud.ccuap.commons.file.FileDTO;
import com.citycloud.ccuap.commons.file.IFileService;
import com.citycloud.ccuap.commons.sys.entity.SysProject;
import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.tc.admin.dto.SysAppDto;
import com.citycloud.ccuap.tc.admin.project.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.tc.admin.entity.SysApp;
import com.citycloud.ccuap.tc.admin.projectrelapp.SysProjectRelAppService;
import com.citycloud.ccuap.tc.common.auth.AuthorizedGrantTypesEnum;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "app信息控制类-SysAppController", value = "SysAppController")
@RestController("SysAppController")
@RequestMapping("/v1/yq/sysApp")
public class SysAppController extends BaseController {

    @Autowired
    private SysAppService sysAppService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IFileService fileService;
    @Value("${server.tomcat.docBase:}")
    private String docBase;
    @Value("${server.file.path:}")
    private String filePath;

    /**
     * 获取认证方式下拉列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getAuthorizedGrantTypes", method = {RequestMethod.POST})
    @ApiOperation(value = "获取认证方式下拉列表", notes = "新增认证应用使用")
    public JSONData<Object> getAuthorizedGrantTypes() {
        List<Map<String, String>> reList = Lists.newArrayList();
        for (AuthorizedGrantTypesEnum temp : AuthorizedGrantTypesEnum.values()) {
            reList.add(ImmutableMap.of("id", temp.getCode(), "text", temp.getName()));
        }
        return JSONData.of("");
    }

    /**
     * 获取应用详情
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSysAppDetail", method = {RequestMethod.GET})
    @ApiOperation(value = "获取应用详情", notes = "getSysAppDetail")
    public JSONData<SysAppVO> getSysAppDetail() {
        String clientId = getStringParameter("clientId");
        return JSONData.of(sysAppService.getSysAppDetail(clientId));
    }

    /**
     * 获取应用详情
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSysAppDetailByProjectId", method = {RequestMethod.GET})
    @ApiOperation(value = "根据projectId获取应用详情", notes = "getSysAppDetailByProjectId")
    public JSONData<SysAppVO> getSysAppDetailByProjectId() {
        Long projectId = getLongParameter("projectId");
        SysProject sysProject = projectService.findById(projectId);

        AppAssert.notNull(sysProject,"站点不存在！！");


        SysAppVO sysAppDetail=sysAppService.getSysAppDetail(sysProject.getClientId());


        return JSONData.of(sysAppDetail);
    }


    /**
     * 获取应用列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/querySysAppPage", method = {RequestMethod.GET})
    @ApiOperation(value = "获取应用列表", notes = "querySysAppPage")
    public JSONData querySysAppPage() {
        PageQuery<Map<String, Object>> pageQuery = ResolveRequest.getPageForParams(this.request);
        return new JSONData(sysAppService.querySysAppPage(pageQuery));
    }

    @RequestMapping(value = "/querySysApps", method = {RequestMethod.GET})
    @ApiOperation(value = "获取未关联应用列表", notes = "querySysApps")
    public JSONData querySysApps() {
        Integer appType = getIntParameter("appType");
        Long projectId = getLongParameter("projectId");
        return new JSONData(sysAppService.querySysApps(appType, projectId));
    }

    /**
     * 增加/修改应用
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveOrUpdate", method = {RequestMethod.POST})
    @ApiOperation(value = "增加/修改应用", notes = "saveOrUpdate")
    public JSONData<Object> saveOrUpdate() {
        SysAppDto dto1 = new SysAppDto();
        dto1.setAppDescribe(getStringParameter("appDescribe"));
        //dto1.setAppId(getLongParameter("appId"));
        dto1.setAppLogo(getStringParameter("appLogo"));
        dto1.setAppName(getStringParameter("appName"));
        dto1.setAppType(getIntParameter("appType"));
        dto1.setClientId(getStringParameter("clientId"));
        dto1.setClientSecret(getStringParameter("clientSecret"));
        dto1.setSecret(getStringParameter("secret"));
        dto1.setWebServerRedirectUri(getStringParameter("webServerRedirectUri"));
        dto1.setAppId(getLongParameter("appId"));
        dto1.setResource(getStringParameter("resource"));
        dto1.setAuthorizedGrantTypes(getStringParameter("authorizedGrantTypes"));
        sysAppService.saveOrUpdate(dto1);
        return JSONData.of("应用创建成功");
    }

    @RequestMapping(value = "/createClientId", method = {RequestMethod.GET})
    @ApiOperation(value = "创建clientId", notes = "createClientId")
    public JSONData createClientId() {
        JSONData jsonData;
        Map<String, String> map = Maps.newHashMap();
        String clientId = getStringParameter("clientId");
        String secret = getStringParameter("secret");
        if (StringUtils.isBlank(clientId)) {
            clientId = UUID.randomUUID().toString().replaceAll("-", "");
        }
        if (StringUtils.isBlank(secret)) {
            secret = UUID.randomUUID().toString().replaceAll("-", "");
        }
        //生成密钥
        String secretEncoder = bCryptPasswordEncoder.encode(secret);
        map.put("clientId", clientId);
        map.put("secret", secret);
        map.put("clientSecret", secretEncoder);
        jsonData = new JSONData(map);
        return jsonData;
    }

    /**
     * 删除应用
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteSysApp", method = {RequestMethod.GET})
    @ApiOperation(value = "删除应用", notes = "deleteSysApp")
    public JSONData deleteSysApp() {
        String clientId = getStringParameter("clientId");
        sysAppService.deleteSysApp(clientId);
        return new JSONData();
    }

    /**
     * 附件上传到服务器
     *
     * @throws Exception
     */
    @PostMapping(value = "/uploadFile")
    @ApiOperation(value = "附件上传到服务器", notes = "上传附件使用")
    public JSONData testUpLoadOss() {
        //String fileName = getStringParameter("fileName");
        MultipartFile file = getFileParameter("file");
        String fileName = null;
        logger.info("name:" + file.getOriginalFilename() + ",fileName:" + file.getName());
        try {
            // 将附件保存到服务器本地
            if (file.isEmpty()) {
                return new JSONData(false, "上传失敗");
            }
            fileName = file.getOriginalFilename();
            File dest = new File(new File(docBase).getAbsolutePath()+ "/" + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest); // 保存文件
                return new JSONData(false, "上传失敗");
            } catch (Exception e) {
                e.printStackTrace();
                return new JSONData(false, "上传失敗");
            }
            //Map<String, String> filsNamesMap = ImmutableMap.of(fileName, filePath);

//            String url = ossService.uploadByFile(MultipartFileToFile.multipartFileToFile(file), file.getOriginalFilename());

        } catch (Exception ex) {
            logger.error("AttachmentController 下 testOss 接口：附件上传到OSS失败！", ex);
            return new JSONData(false, "上传失敗");
        }finally {
            Map<String, String> map = Maps.newHashMap();
            map.put("url",filePath+fileName);
            return new JSONData(map,"上传成功");
        }
    }
}